<template>
    <div class="e-form">
        <BillTop title="操作手考核编辑" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
            <!-- 基本信息 -->
            <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
            <el-tab-pane label="考核明细" name="records" :disabled="clickTabFlag"></el-tab-pane>
            <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="form" :model="formData.operator" label-width="150px" :rules="rules" >
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="操作手：" prop="operator">
                                            <el-input v-model="formData.operator.operator" :readonly="isNameSelect">
                                                <i slot="suffix" class="el-input__icon el-icon-document-copy"  @click="selectName"></i>
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="联系电话：" prop="phoneNo">
                                            <el-input v-model="formData.operator.phoneNo" maxlength="11" :readonly="isNameSelect"
                                            v-enter-number="{
                                                set: formData,
                                                val: 'operator',
                                                key: 'phoneNo'
                                            }">
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="身份证号：" prop="idCard">
                                            <el-input v-model="formData.operator.idCard" :readonly="isNameSelect">
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="性别：" prop="gender">
                                            <el-radio-group v-model="formData.operator.gender" :disabled="isNameSelect">
                                                <el-radio :label="0">女</el-radio>
                                                <el-radio :label="1">男</el-radio>
                                            </el-radio-group>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="工作状态：" prop="workState">
                                            <span>{{formData.operator.workState ? workStatus[formData.operator.workState].label : ''}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="考核时间：">
                                            <el-date-picker
                                                v-model="formData.operator.billDate"
                                                type="date"
                                                placeholder="选择日期"
                                                value-format="yyyy-MM-dd"
                                                :clearable="false"
                                            >
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="考核分数：">
                                            <span>{{formData.operator.assessmentFraction}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="考核机构：">
                                            <span> {{formData.operator.orgName}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="recordsCon" class="con">
                        <div class="tabs-title" id="records">考核明细</div>
                        <div class="e-table">
                            <div class="errorMsg" v-if="errorAssessMsg.length>0">
                                <span v-for="item,index in errorAssessMsg" :key="index">
                                    {{item}}
                                </span>
                            </div>
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                :data="operatorAssessment"
                                border
                                ref="planTable"
                                v-sortTable="{ 'tableData': operatorAssessment, '_this': this, 'ref': 'planTable' }"
                            >
                                <el-table-column  fixed type="index" label="序号" width="80" align="center">
                                </el-table-column>
                                <el-table-column
                                    prop="assessmentContent"
                                    align="center"
                                    min-width="300"
                                    show-overflow-tooltip
                                    label="考评内容"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="assessmentFraction"
                                    label="分数"
                                    width="300"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.assessmentFraction" clearable  @input="rowCurChangeTable(row)" @blur="collectGrade"
                                        v-enter-integer1="{
                                            set:row,
                                            key:'assessmentFraction'
                                        }"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="attachId" bucketName="facilitybase" />
                    </div>

                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <el-button
                type="primary"
                size="small"
                class="btn-blue"
                @click="preserve"
                v-debounce
                >保存</el-button
            >
            <el-button
                type="primary"
                size="small"
                class="btn-delete"
                @click="deleteBill"
                v-debounce
                >删除</el-button
            >
            <el-button size="small" @click="handleClose" v-debounce>取消</el-button>
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import $ from 'jquery'
import request from '@/api/equip/operatorManagement.js'
import '@/utils/jquery.scrollTo.min'
import AttachComp from '@/components/common/attachIndex'
import { hideLoading, selectDataClient } from '@/utils/common'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            selectEquipVisible: false,
            tableData: [],
            formData: {
                'operator': {
                    'assessmentFraction': 0,
                    'billDate': '',
                    'billId': '',
                    'founderId': '',
                    'founderName': '',
                    'gender': '',
                    'gmtCreate': '',
                    'gmtModified': '',
                    'idCard': '',
                    'initial': '',
                    'operator': '',
                    'operatorId': '',
                    'orgId': '',
                    'orgName': '',
                    'phoneNo': '',
                    'recorder': '',
                    'recorderId': '',
                    'workState': null
                },
            },
            operatorAssessment: [], //考核明细列表
            billid: this.$route.query.billid,
            switchNum: 0,
            rules: {
                operator: [
                    { required: true, message: '请选择操作手', trigger: 'change'  },
                ],
                phoneNo: [
                    { required: true, message: '请输入电话', trigger: ['blur', 'change'] },
                ],
                idCard: [
                    { required: true, message: '请输入身份证', trigger: ['blur', 'change'] },
                ],
                gender: [
                    { required: true, message: '请选择性别', trigger: ['blur', 'change'] },
                ],
                workState: [
                    { required: true, message: '请选择工作状态', trigger: 'change' },
                ],
                billDate: [
                    { required: true, message: '请选择考核时间', trigger: 'change' },
                ],
            },
            errorList: [], //控制导航栏感叹号的显示
            errorAssessMsg: [], //错误显示
            currentRow: {}, //当前行数据
            isNameSelect: true
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            workStatus: state=>state.equip.equipData.workStatus,
            assessmentLevel: state=>state.equip.equipData.assessmentLevel,
        }),
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.$route.query.billid
        },
    },
    components: {
        AttachComp
    },
    created () {
        this.init()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'records', 'attach']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    console.log('item', item)
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()

    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //弹窗选择名字
        selectName () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/facilitybase/operator/assess/get/operator', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                Title: '人员选择' // 标题
            }).then(val => {
                this.setSelectedInfo(val)
                val[0].orgName = this.formData.operator.orgName
                val[0].orgId = this.formData.operator.orgId
                val[0].billId = this.formData.operator.billId
                this.formData.operator = Object.assign(this.formData.operator, val[0])
            })
        },
        //初始化数据
        init () {
            Promise.all([
                this.getInfo(),
                this.getAssessDtl(),
            ]).finally(() => {
                hideLoading()
            })
        },
        //获取操作手基本信息
        getInfo () {
            request.getOperatorAssessBase(this.billid).then(res=>{
                this.formData.operator = res
            })
        },
        //获取操作手考核明细
        getAssessDtl () {
            request.getOperatorAssessDtl(this.billid).then(res=>{
                this.operatorAssessment = res
            })
        },
        //考核分数汇总
        collectGrade () {
            this.operatorAssessment.forEach(item=>{
                this.formData.operator.assessmentFraction += +item.assessmentFraction
            })
        },
        //判断当前状态是否修改
        rowCurChangeTable (row) {
            if (row.changeType === 2) return
            this.currentRow = row
            this.currentRow.changeType = 2
        },
        //验证考核明细
        verifyAssess () {
            return  new Promise((resolve, reject)=>{
                this.errorAssessMsg = []
                this.operatorAssessment.forEach((item, index)=>{
                    if(item.assessmentFraction == '' || item.assessmentFraction == null) {
                        let str = `第 ${index + 1} 行的（分数）不能为空`
                        this.errorAssessMsg.push(str)
                    }
                })
                if(this.errorAssessMsg.length > 0) {
                    this.isErrorFileMsg = true
                    reject()
                }else{
                    this.errorAssessMsg = false
                    resolve()
                }
            })
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                this.$refs.form.validate(valid => {
                    if(valid) {
                        request.updateOperatorAssessBase(this.formData.operator).then(()=>{
                            resolve()
                        })
                            .catch(err=>{
                                reject(err)
                                this.setError('baseInfo')
                            })
                    }else{
                        reject()
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //更新考核明细
        updateAssessDtl () {
            return new Promise((resolve, reject)=>{
                this.verifyAssess().then(()=>{
                    request.updateOperatorAssessDtl(this.operatorAssessment).then(()=>{
                        resolve()
                    })
                        .catch(err=>{
                            reject(err)
                            this.setError('records')
                        })
                }).catch(()=>{
                    reject()
                    this.setError('records')
                    this.scorllError()
                })

            })
        },
        //保存
        preserve () {
            this.errorList = []
            Promise.all([
                this.updateBaseInfo(),
                this.updateAssessDtl()
            ])
                .then(() => {
                    this.clientPop('suc', '保存成功', this.handleClose)
                    this.init()
                })
                .catch(() => {
                    this.clientPop('err', '保存失败', ()=>{
                        this.scorllError()
                    })
                })
                .finally(() => {
                    hideLoading()
                })
        },
        //删除单据
        deleteBill () {
            this.clientPop('info',  this.oneDeleteErr, ()=>{
                request.operatorAssessDelete(this.billid ).then(()=>{
                    this.clientPop('suc', '删除成功', this.handleClose)
                })
            })
        },
        //取消
        handleClose () {
            this.$router.replace('/operatorAssessList')
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;
}

.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
